package com.xunmeng.chapter2;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import static com.xunmeng.chapter1.ByteBufferUtil.debugRead;

@Slf4j
public class Server {

    public static void main(String[] args) throws IOException {
        // 创建缓存数组
        ByteBuffer buffer=ByteBuffer.allocate(1024);
        // 创建服务器
        ServerSocketChannel ssc=ServerSocketChannel.open();

        // 绑定接口
        ssc.bind(new InetSocketAddress(8080));
        List<SocketChannel> channelList=new ArrayList<>();
        // 接收数据
        log.info("成功建立开启服务。。。。。。。");
        while (true){
            // 获取与客户通信的channel
            SocketChannel sc = ssc.accept();
            log.warn("新的客户端与服务端建立了连接====>{}",sc);
            channelList.add(sc);
//            for (SocketChannel socketChannel : channelList) {
//                // 读取chaannel的内容
//                socketChannel.read(buffer);
//                buffer.flip();
//                log.info("读取到客户端{}的信息：");
//                StringBuilder stringBuilder = debugRead(buffer);
//                buffer.clear();
//            }
            // 为每一个连接创建线程
            (new Thread(new Runnable() {
                @Override
                public void run() {
                    ByteBuffer byteBuffer=ByteBuffer.allocate(16);
                    while (true){
                        try {
                            sc.read(byteBuffer);
                            // 打印
                            byteBuffer.flip();
                            log.warn("服务器接收到{}客户端接收到消息：{}",sc,StandardCharsets.UTF_8.decode(byteBuffer));
                            byteBuffer.clear();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            })).start();
        }

    }
}
